#include "MenuWin.h"

MenuWin::MenuWin(WINDOW *win, const std::vector<std::string> &choices)
    : selected_index(0)
{
    int h, w;
    getmaxyx(win, h, w);
    menu_win = derwin(win, h - 2, w - 2, 1, 1);
    for (auto it = choices.begin(); it != choices.end(); ++it)
    {
        items.push_back(new_item(it->c_str(), ""));
    }
    items.push_back(nullptr); // 结束标志
    menu = new_menu(items.data());
    set_menu_win(menu, win);
    set_menu_sub(menu, menu_win);
    set_menu_format(menu, 0, 0);
    set_menu_mark(menu, " * ");
    set_menu_spacing(menu, 1, 1, 1);
    set_menu_grey(menu, 1);
}

MenuWin::~MenuWin()
{
    unpost_menu(menu);
    free_menu(menu); // 删除菜单
    for (auto it = items.begin(); it != items.end(); ++it)
    {
        free_item(*it);
    } // 删除菜单项
    delwin(menu_win);
}

int MenuWin::run()
{
    post_menu(menu);
    wrefresh(menu_win);
    int ch;
    while ((ch = getch()) != 10) // Enter
    {
        switch (ch)
        {
        case KEY_UP:
            menu_driver(menu, REQ_UP_ITEM);
            break;
        case KEY_DOWN:
            menu_driver(menu, REQ_DOWN_ITEM);
            break;
        case 'q':
            return -1; // 退出
        default:
            break;
        }
        wrefresh(menu_win);
    }
    selected_index = item_index(current_item(menu));

    return selected_index;
}
